﻿using Brilliant_see.Core.AbstractClass;
using Brilliant_see.Core.structs;
using CommunityToolkit.Mvvm.ComponentModel;
using System.Collections.ObjectModel;

namespace Brilliant_see.App.ViewModels;

public partial class ComicBrowseViewModel : ObservableObject
{
    private readonly Timer _timer;
    private Comic? _comic;

    [ObservableProperty]
    private Chapter? _chapter;

    [ObservableProperty]
    private int _currentPageIndex = 1;

    [ObservableProperty]
    private int _pageCount = 50;

    /// <summary>
    /// 当前时间
    /// </summary>
    public string CurrentTime => DateTime.Now.ToString("HH:mm");

    public ObservableCollection<string> Images { get; set; } = new();

    public ComicBrowseViewModel()
    {
        _timer = new Timer((o) => { OnPropertyChanged(nameof(CurrentTime)); }, null, (60 - DateTime.Now.Second) * 1000, 60000);
    }

    /// <summary>
    /// 设置浏览器的漫画和章节
    /// </summary>
    /// <param name="comic"></param>
    /// <param name="chapter"></param>
    public void SetComicOrChapter(Comic comic, ref Chapter chapter)
    {
        _comic = comic;
        Chapter = chapter;

        LoadChapterPicAsync(chapter);
    }

    /// <summary>
    /// 载入章节图片
    /// </summary>
    /// <param name="chapter"></param>
    private Task LoadChapterPicAsync(Chapter chapter) => Task.Run(() =>
    {
        var picEnumerator = _comic!.ComicSource.GetPicEnumerator(chapter);

        int i = 0;
        while (picEnumerator.MoveNext())
        {
            Images.Add(picEnumerator.Current);

            Thread.Sleep(200);
            i++;
        }

        PageCount = i;
    });
}